# import pytest
from selenium import webdriver
import unittest, time
from contrast import ImageCompare
# from ddt import ddt,data
from public import *
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import shutil
import datetime
import logging
from logger import *
import os
# from PIL import ImageGrab
import requests
import xlrd, xlwt
from xlutils.copy import copy
from test_send_email import *

# class TestAutomation:
import sys

sys.setrecursionlimit(10000)

number = 18328578991
pwd = 123456
# 拷贝驱动文件到目录下
dir1 = 'C:\\CTDebug\HandSwitch\\HandSwitchOn.txt'
dir2 = 'C:\\CTDebug'


def set_sum(i):
    sum = i
    return sum


file_name = None


def create_excel(d):
    global file_name
    ws = xlwt.Workbook()
    sheet = ws.add_sheet("CBCT曝光上传")
    sheet.write(0, 0, '虚拟驱动自动化测试')
    sheet.write(0, 1, "设置运行次数")
    sheet.write(1, 1, "{}".format(d))
    sheet.write(0, 2, "实际运行次数")
    sheet.write(0, 3, "上传成功次数")
    sheet.write(0, 4, "上传失败次数")
    sheet.write(0, 5, "卡住次数")
    sheet.write(1, 0, "CT上传")
    file_name = ".\\reports\\CBCT_CT上传测试{}.xls".format(time.strftime('%Y-%m-%d-%H'))
    ws.save(file_name)


def write_excel(a, b, value):
    data = xlrd.open_workbook(file_name)
    workbook = copy(data)
    sheet_write = workbook.get_sheet(0)
    value = str(value)
    sheet_write.write(a, b, value)
    workbook.save(file_name)


def login_():
    driver = webdriver.Chrome()
    driver.get('http://127.0.0.1:8189/#/')
    driver.implicitly_wait(120)
    driver.maximize_window()
    driver.find_element_by_xpath('//*[@id="app"]/div/div/div[1]/div[1]/form/div[1]/div/div/div/input').send_keys(
        number)  # 输入手机号
    driver.find_element_by_xpath('//*[@id="app"]/div/div/div[1]/div[1]/form/div[2]/div/div/div/input').send_keys(
        pwd)  # 输入密码
    driver.find_element_by_xpath('//div[@class="zh_postForm"]').click()  # 点击登录
    return driver


# global i


ct_a = 0  # 上传成功
ct_b = 0  # 上传失败
ct_c = 0  # 准备进度卡住


def create_contexts(path):
    isExists = os.path.exists(path)
    if not isExists:
        print(path)
        os.mkdir(path)
        return path

    else:
        # print('已存在！')
        return path


def create_test_contexts(path):
    isExists = os.path.exists(path)
    if not isExists:
        print(path)
        os.makedirs(path)
        return path

    else:
        # print('已存在！')
        return path


def test_01_CT_shooting(i, c, path, path2):
    logging.info('CT开始时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
    logging.info('test_01_CT_shooting第{}次'.format(i))
    write_excel(1, 2, i)
    if c:
        driver = c
        # logging.info('test_01_CT_shooting_第{}次'.format(i))
        time.sleep(8)

        driver.find_element_by_xpath('//div[text()="登记"]').click()  # 进入登记页
        time.sleep(1)
        patient_name = random_name()
        driver.find_element_by_xpath('//input[@placeholder="患者姓名" and @class="yg-input__inner" ]').send_keys(
            "{}".format(patient_name))  # 输入患者姓名参数化
        time.sleep(1)
        driver.find_element_by_xpath('//div[@id="cbctCT"]').click()  # 选择拍摄模式
        driver.find_element_by_xpath('//div[@class="check-in-wrap"]/following-sibling::div[1]//div[2]').click()  # 点击下一步
        time.sleep(1)
        driver.find_element_by_xpath('//button[@id="cbctOkct"]').click()  # 点击确确定

        try:
            progress_locator = (By.XPATH, '//div[contains(text()," 准备完成")]')  # 等待准备完成元素可见
            WebDriverWait(driver, 90, 1).until(EC.visibility_of_element_located(progress_locator))
            time.sleep(1)
            driver.find_element_by_xpath('//div[@id="cbctFinishct"]').click()  # CT点击下一步
            shutil.copy(dir1, dir2)  # 复制手闸文件到CTDebug目录
            time.sleep(120)  # 等待采集曝光完成

            # 智能等待-等待元素可见与不可见--------------------------------------
            # time.sleep(2)
            # WebDriverWait(driver, 1200, 3).until(EC.visibility_of_element_located((By.XPATH,'//span[@class="nsel close-btn"]')))
            # WebDriverWait(driver, 1200, 3).until_not(EC.visibility_of_element_located((By.XPATH, '//div[@class="circle_proc"]')))
            # time.sleep(2)

            dic_file = create_contexts(path)  #
            filepath = '{}\\{}.png'.format(dic_file, str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
            driver.save_screenshot(filepath)
            time.sleep(3)


            driver.find_element_by_xpath('//span[@class="nsel close-btn"]').click()  # CT叉掉元素
            time.sleep(5)
            driver.find_element_by_xpath('//div[text()="已检查"]').click()  # 已检查元素
            try:
                loc_upload = (By.XPATH, '//div[contains(text(),"已上传")]')
                if WebDriverWait(driver, 180, 1).until(EC.visibility_of_all_elements_located(loc_upload)):
                    logging.info('CT上传成功')
                    global ct_a
                    ct_a += 1
                    write_excel(1, 3, ct_a)
            except:
                logging.info('CT上传失败')
                global ct_b

                ct_b += 1
                write_excel(1, 4, ct_b)

            logging.info('CT结束时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
            return driver
        except:
            dics_files = create_test_contexts(path2)
            error_filepath1 = '{}\\{}.png'.format(dics_files,
                                                 str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
            driver.save_screenshot(error_filepath1)
            error_filepath2 = 'D:\\ycw\\CTscreenshot-\\error\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
            driver.save_screenshot(error_filepath2)
            global ct_c
            ct_c += 1
            write_excel(1, 5, ct_c)
            logging.error("CT{}进度卡住！！！".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
            driver.quit()


def is_ele_exist(self, ele):
    if ele:
        return True
    else:
        return False


if __name__ == '__main__':
    f = open('./gggg')
    d = f.read()
    d = int(d)
    create_excel(d)
    start_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    write_excel(5, 0, "开始时间")
    write_excel(5, 1, start_time)
    num = 20
    try:
        for x in range(d // num):

            c = login_()
            for i in range(num):
                if c:
                    path1 = 'E:\CTscreenshot' + str(datetime.datetime.now().strftime('%Y%m%d'))
                    path2 = path1 + '\\error'
                    a = test_01_CT_shooting(x * num + i + 1, c, path1, path2)
                else:
                    break

            if c != None:
                c.quit()
            else:
                pass
    except Exception as e:
        logging.info(e)
    finally:
        finally_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        write_excel(6, 0, "停止时间")
        write_excel(6, 1, finally_time)

        # yag = yagmail.SMTP(user="15071312445@163.com", password="XKIXZZCRKYPBWWJS", host='smtp.163.com')
        # # rev_email = 'yi.deng@dentalink.com.cn'
        # # rev_email3 = 'ping.liu@fussenct.com'
        # # rev_email4 = 'lingbing.zeng@fussenct.com'
        #
        # rev_email1 = 'chuanqi.jiang@fussenct.com'
        # rev_email2 = 'liang.ding@fussenct.com'
        # title = '【虚拟驱动】发送附件CBCT测试结果'
        # contents = ['【虚拟驱动】对面电脑CBCT压力稳定性结果统计']
        file_path = FindNewFile().get_new_file('.\\reports')
        # file_path2 = FindNewFile().get_new_file('.\\logs')
        #
        # # yag.send() #收件人邮箱 标题 正文 附件地址
        # yag.send([rev_email1, rev_email2], title, contents, [file_path, file_path2])
